const App = getApp();
const db = wx.cloud.database();
const _ = db.command;
let that
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 评阅弹窗
    show: false,
    // 成员信息详情展开 
    baseMemberShow: true,
    // 成绩
    results: false,
    // 实习前中后展开
    InternshipShowStart: false,
    InternshipShowOngoing: false,
    InternshipShowEnd: false,
    // 点击的是哪个实习价段的值
    InternshipKey: "",
    // 实践基地详情
    BaseData: {},
    // 成员详情
    memberDetails: "",
    // 显示fab
    fabShow: false,
    // 笼罩层
    overlayShow: false,
    // 菜单列表
    Menulist: [{
        name: "上传实习前材料",
        icon: "icon-shangchuan",
        bg: "repeating-linear-gradient(45deg, #00d1FF, #69FF97)",
        path: "",
        key: "Start"
      }, {
        name: "上传实习中材料",
        icon: "icon-shangchuan",
        bg: "repeating-linear-gradient(45deg, #ED1C24, #FECE12)",
        key: "Ongoing"

      },
      {
        name: "上传实习结束材料",
        icon: "icon-shangchuan",
        bg: " repeating-linear-gradient(45deg, #24FE41, #F7FD47)",
        path: "",
        key: "End"
      },

    ],
    // 下载弹窗
    modalName: "",
    // 详情弹窗
    folderDetailsShow: "",
    // 文件详情
    folderDetails: "",
    // 下载回来的文件链接地址
    downloadFilePath: "",
    // 成绩打分
    results: "",
    // 选择成绩下标
    pickerIdx: null,
    // 选择成绩数组
    picker: ['优秀', '良好', '及格', '不及格'],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    that = this
    let data = JSON.parse(decodeURIComponent(options.passData));
    console.log('传值后', data);
    let UserInfo = App.cache.getUserInfo()
    console.log('获取用户信息:', UserInfo);
    delete UserInfo._id
    that.setData({
      UserInfo: UserInfo,
      practiceBaseId: data.practiceBaseId,
      // 获取传值过来的成员的学号
      memberAccount: data.account,
      removeId: data.removeId
    })
    that.getpracticeBase()
    that.getpracticeBaseFile()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  // 打开评阅弹窗
  showPopup() {
    this.setData({
      show: true
    });
  },
  // 关闭评阅弹窗
  onClose() {
    this.setData({
      show: false
    });
  },
  // 成绩
  bindPickerChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    let picker = that.data.picker
    that.setData({
      pickerIdx: e.detail.value,
      results: picker[e.detail.value]
    })
  },
  // fab
  fabShow() {
    that.setData({
      overlayShow: !that.data.overlayShow,
      fabShow: !that.data.fabShow
    });
  },
  // 关闭fab和笼罩层
  onClickHide() {
    that.setData({
      overlayShow: false,
      fabShow: false
    });
  },
  // 成员展开
  baseMemberShow() {
    that.setData({
      baseMemberShow: !that.data.baseMemberShow
    })
  },
  // 成绩展开
  baseResultsShow() {
    that.setData({
      results: !that.data.results
    })
  },
  // 实习前中后展开
  InternshipShow(e) {
    let key = e.currentTarget.dataset.key
    console.log(key);
    that.setData({
      [`InternshipShow${key}`]: !that.data[`InternshipShow${key}`],
      InternshipKey: key
    })
  },

  // 下载文件到本地
  downloadFile(e) {
    let fileid = e.currentTarget.dataset.fileid
    console.log('fileid', fileid);
    // 如果是打开详情再下载的，那就把详情弹窗关掉先
    that.setData({
      folderDetailsShow: ""
    })
    App.toast.showLoading('下载中')
    wx.cloud.getTempFileURL({
      fileList: [{
        fileID: fileid,
      }]
    }).then(res => {
      App.toast.hideLoading()
      console.log('返回来的链接', res.fileList[0])
      that.setData({
        modalName: "downloadShow",
        downloadFilePath: res.fileList[0].tempFileURL,
      })
    }).catch(error => {
      console.error(error)
    })
  },
  // 关闭下载弹窗
  hideModal(e) {
    this.setData({
      modalName: null
    })
  },

  // 打开详情弹窗
  DetailsShow(e) {
    let data = e.currentTarget.dataset.data
    let key = e.currentTarget.dataset.key
    data.key = key
    console.log('data', data);
    console.log('key', key);
    that.setData({
      folderDetails: data,
      folderDetailsShow: 'DetailsShow',
    })
  },
  // 关闭详情弹窗
  CloseFolderDetails(e) {
    this.setData({
      folderDetailsShow: ""
    })
  },

  // 复制文件链接地址
  codeFilePath(e) {
    console.log(e.currentTarget.dataset);
    let filepath = e.currentTarget.dataset.filepath
    wx.setClipboardData({
      data: filepath,
      success: res => {
        console.log(res);
        App.toast.showToast('链接已经复制', 'none', 1000)
        that.hideModal()
      }
    })
  },
  // 获取实践基地详情
  getpracticeBase() {
    App.toast.showLoading('加载中')
    db.collection('practiceBase').where({
        practiceBaseId: that.data.practiceBaseId
      })
      .get({
        success: function (res) {
          App.toast.hideLoading()
          console.log('获取实践基地详情', res.data[0])
          let BaseData = res.data[0]
          // 获取成员详情
          let memberDetails = BaseData.members.filter(item => {
            return item.account === that.data.memberAccount
          })
          console.log('memberDetails', memberDetails[0]);
          that.setData({
            BaseData: BaseData,
            memberDetails: memberDetails[0]
          })
        }
      })
  },
  // 获取实践基地文件详情
  getpracticeBaseFile() {
    App.toast.showLoading('加载中')
    db.collection('practiceBaseFile').where({
        practiceBaseId: that.data.practiceBaseId,
        account: that.data.memberAccount
      })
      .get({
        success: function (res) {
          App.toast.hideLoading()
          console.log('获取实践基地文件详情', res.data[0])
          that.setData({
            membersList: res.data[0]
          })
        }
      })
  },
  // 获取用户点击了那个实习阶段的key
  getInternshipKey(e) {
    console.log(e.currentTarget.dataset.key);
    that.setData({
      InternshipKey: e.currentTarget.dataset.key
    })
    // 上传附件
    that.addfile()
  },

  // 上传附件
  addfile() {
    // 关闭笼罩层
    that.onClickHide()
    wx.chooseMessageFile({
      count: 50,
      type: 'all',
      success(res) {
        console.log(res);
        let data = res.tempFiles
        console.log(data);
        App.toast.showLoading('上传中')
        const uploadTasks = data.map((file, index) => {
          let cloudPath = "实践基地附件/" + that.data.BaseData.name + '/' + file.name
          return wx.cloud.uploadFile({
            cloudPath: cloudPath,
            filePath: file.path
          });
        });
        Promise.all(uploadTasks)
          .then(res => {
            App.toast.hideLoading()
            let list = []
            res.forEach((item, index) => {
              list.push({
                name: data[index].name,
                size: (data[index].size / 1024 / 1024).toFixed(2),
                id: item.fileID,
                type: data[index].type,
                fileId: Date.now() + index,
                timeTs: Date.now()
              })
            })
            console.log('list', list);
            return list
          })
          .then(list => {
            let InternshipKey = that.data.InternshipKey
            switch (InternshipKey) {
              case 'Start':
                that.addStartFile(list)
                break;
              case 'Ongoing':
                that.addOngoingFile(list)
                break;
              case 'End':
                that.addEndFile(list)
                break;

              default:
                App.toast.showToast('出现不可预知的错误')
                break;
            }
          })
          .catch(e => {
            App.toast.hideLoading()
            console.log(e);
          });
      },
      fail: function (res) {}
    })
  },
  // 上传实习前材料
  addStartFile(file) {
    console.log('addStartFile提交的file', file);
    App.toast.showLoading('提交中')
    db.collection('practiceBaseFile').where({
      practiceBaseId: that.data.practiceBaseId,
      account: that.data.memberAccount
    }).update({
      data: {
        StartFile: _.push(file)
      },
      success: function (res) {
        App.toast.hideLoading()
        console.log('提交成功', res);
        that.getpracticeBaseFile()
        that.setData({
          InternshipShowStart: true,
        })
      }
    })
  },
  // 上传实习中材料
  addOngoingFile(file) {
    console.log('addOngoingFile提交的file', file);
    App.toast.showLoading('提交中')
    db.collection('practiceBaseFile').where({
      practiceBaseId: that.data.practiceBaseId,
      account: that.data.memberAccount
    }).update({
      data: {
        OngoingFile: _.push(file)
      },
      success: function (res) {
        App.toast.hideLoading()
        console.log('提交成功', res);
        that.getpracticeBaseFile()
        that.setData({
          InternshipShowOngoing: true,

        })
      }
    })
  },
  // 上传实习后材料
  addEndFile(file) {
    console.log('addEndFile提交的file', file);
    App.toast.showLoading('提交中')
    db.collection('practiceBaseFile').where({
      practiceBaseId: that.data.practiceBaseId,
      account: that.data.memberAccount
    }).update({
      data: {
        EndFile: _.push(file),
        Submit: true
      },
      success: function (res) {
        App.toast.hideLoading()
        console.log('提交成功', res);
        that.getpracticeBaseFile()
        that.setData({
          InternshipShowEnd: true,
        })
      }
    })
  },

  // 移除成员
  removeMember(e) {
    wx.showModal({
      title: '提示',
      content: '确定移除该成员吗',
      success(res) {
        if (res.confirm) {
          App.toast.showLoading('加载中')
          db.collection('practiceBase').where({
              practiceBaseId: that.data.practiceBaseId,
              'members.account': that.data.memberAccount,
            }).update({
              data: {
                members: _.pull({
                  account: that.data.memberAccount,
                })
              }
            })
            .then(res => {
              db.collection('practiceBaseFile').doc(that.data.removeId).remove({
                success: function (res) {
                  App.toast.hideLoading()
                  console.log('移出成功', res);
                  App.route.relBack('/pages/practiceBase/details/index')
                }
              })
            })

        } else if (res.cancel) {
          console.log('取消移除');
        }

      }
    })
  },
  // 成员删除自己的文件
  memberRemoverFolder(e) {
    let folder = e.currentTarget.dataset.folder
    console.log(folder);
    if (folder.key == 'Start') {
      db.collection('practiceBaseFile').where({
        practiceBaseId: that.data.practiceBaseId,
        account: that.data.memberAccount,
        'StartFile.fileId': folder.fileId
      }).update({
        data: {
          StartFile: _.pull({
            fileId: folder.fileId
          })
        },
        success: function (res) {
          console.log('删除成功', res);
          App.toast.hideLoading()
          that.getpracticeBaseFile()
          that.CloseFolderDetails()
        }
      })
    } else if (folder.key == 'Ongoing') {
      db.collection('practiceBaseFile').where({
        practiceBaseId: that.data.practiceBaseId,
        account: that.data.memberAccount,
        'OngoingFile.fileId': folder.fileId
      }).update({
        data: {
          OngoingFile: _.pull({
            fileId: folder.fileId
          })
        },
        success: function (res) {
          console.log('删除成功', res);
          App.toast.hideLoading()
          that.getpracticeBaseFile()
          that.CloseFolderDetails()
        }
      })
    } else {
      db.collection('practiceBaseFile').where({
        practiceBaseId: that.data.practiceBaseId,
        account: that.data.memberAccount,
        'EndFile.fileId': folder.fileId
      }).update({
        data: {
          EndFile: _.pull({
            fileId: folder.fileId
          })
        },
        success: function (res) {
          console.log('删除成功', res);
          App.toast.hideLoading()
          that.getpracticeBaseFile()
          that.CloseFolderDetails()
        }
      })
    }

  },
  // 评阅
  addResults() {
    wx.showModal({
      title: '提示',
      content: '请确认实习已经结束',
      success(res) {
        if (res.confirm) {
          App.toast.showLoading('提交中')
          db.collection('practiceBaseFile').where({
            practiceBaseId: that.data.practiceBaseId,
            account: that.data.memberAccount
          }).update({
            data: {
              Review: true,
              results: that.data.results
            },
            success: function (res) {
              App.toast.hideLoading()
              console.log('提交成功', res);
              App.route.relBack('/pages/practiceBase/details/index')
            }
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
})